package com.mycode.test;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static com.mycode.util.ByteBufferUtil.debugAll;

/**
 * 利用多线程技术，提高吞吐量
 */
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        Selector boss = Selector.open();
        SelectionKey bossKey = serverSocketChannel.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);

        serverSocketChannel.bind(new InetSocketAddress(8080));

        // 创建Worker数组
        // 获取可用核心数 但是在docker容器下，拿到的是真实物理机的核心数 JDK10 才修复
        int coreNum = Runtime.getRuntime().availableProcessors();
        Worker[] workers = new Worker[2];
        for (int i = 0; i < 2; i++) {
            workers[i] = new Worker("worker-" + i);
        }

        AtomicInteger index = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    log.debug("connecting...:{}", socketChannel.getRemoteAddress());

                    // 2. 关联 worker selector
                    log.debug("worker register before ...:{}", socketChannel.getRemoteAddress());
                    // round robin 轮训算法
                    workers[index.getAndIncrement() % workers.length].register(socketChannel);

                    log.debug("worker register after ...:{}", socketChannel.getRemoteAddress());


                }
            }
        }
    }

    /**
     * 单 worker 版本
     * @throws IOException
     */
    private static void singleWorker() throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        Selector boss = Selector.open();
        SelectionKey bossKey = serverSocketChannel.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);

        serverSocketChannel.bind(new InetSocketAddress(8080));

        // 创建固定数据的 Worker
        Worker worker = new Worker("worker-0");


        while (true) {
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    log.debug("connecting...:{}", socketChannel.getRemoteAddress());

                    // 2. 关联 worker selector
                    log.debug("worker register before ...:{}", socketChannel.getRemoteAddress());
                    worker.register(socketChannel);

                    log.debug("worker register after ...:{}", socketChannel.getRemoteAddress());


                }
            }
        }
    }

    // work Group
    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;
        // 任务交互 boss Thread 和 worker Thread 进行信息交互
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程 和 selector
         */
        public void register(SocketChannel socketChannel) throws IOException {
            // 代码是 bossGroup Thread 执行如下代码
            if (!start) {
                thread = new Thread(this, name);
                selector = Selector.open();
                thread.start();
                start = true;
            }
            // 向队列添加了任务
            queue.add(() -> {
                try {
                    socketChannel.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            // 唤醒 selector worker Thread 可能会在 selector.select() 处阻塞
            // 即使 wakeup() 先于 select() 执行，程序执行到 select() 也不会阻塞，立即往下执行
            selector.wakeup();

        }

        @Override
        public void run() {
            // worker Thread 线程执行如下代码
            while (true) {
                try {
                    selector.select(); // 阻塞
                    // 取出 boss Thread 放入的任务，交给 worker Thread 运行
                    Runnable task = queue.poll();
                    if (task != null) {
                        // 在这个位置 执行了 socketChannel.register(selector, SelectionKey.OP_READ, null);
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                            SocketChannel socketChannel = (SocketChannel) key.channel();
                            log.debug("read...{}", socketChannel);
                            socketChannel.read(byteBuffer);
                            byteBuffer.flip();
                            debugAll(byteBuffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
